import { View, Text } from "@tarojs/components";
import {
  Form,
  Cell,
  Input,
  Button,
  Uploader,
  Textarea,
  Toast,
} from "@taroify/core";
import HeaderSearch from "@/components/HeaderSearch/index";
import Header from "@/components/Header/index";
import GoodsTitle from "@/components/GoodsTitle/index";
import Footer from "@/components/Footer/index";
import { useEffect, useRef, useState } from "react";
import { requestPOST } from "@/request";
import Taro from "@tarojs/taro";
export default function Index() {
  const [info, setInfo] = useState<any>({
    businessLicense: "",
    enterpriseFamous: "",
    identityCard: "",
  });

  const getInfo = () => {
    requestPOST("shop/getShopUploadInformation").then((res) => {
      setInfo(res);
    });
  };

  const onSubmit = () => {
    requestPOST("shop/shopInformationUpload", { ...info }).then(() => {
      Toast.open({ type: "success", message: "保存成功" });
      formRef.current?.reset();
    });
  };

  const priviewImage = (sources, current, type = "image") => {
    sources =
      sources &&
      sources
        .split(",")
        .map((item) => ({ url: process.env.TARO_APP_API + item, type }));
    Taro.previewMedia({
      sources: sources || [],
      current: current,
    });
  };

  const onUpload = (key, limit = 0) => {
    Taro.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
    }).then(({ tempFiles, tempFilePaths }) => {
      const size = tempFiles[0].size;
      if (size > 500 * 1024) {
        return Toast.open({ type: "fail", message: "大小超过500kb无法上传" });
      }
      Taro.showLoading({
        title: "上传中...",
      });
      Taro.uploadFile({
        url: process.env.TARO_APP_API + "/other/upload",
        filePath: tempFilePaths[0],
        name: "file",
        success(res) {
          Taro.hideLoading();
          const { relativeUrl } = JSON.parse(res.data).data;
          setInfo({
            ...info,
            [key]: limit
              ? `${info[key] ? info[key] + "," : ""}${relativeUrl}`
              : relativeUrl,
          });
        },
        fail() {
          Toast.open({ type: "fail", message: "upload error" });
        },
      });
    });
  };

  useEffect(() => {
    getInfo();
  }, []);

  const formRef = useRef<any>();
  return (
    <View className="taroBox">
      <HeaderSearch />
      <Header />
      <View>
        <GoodsTitle title="证件图片上传" isMore={false} />
        <View>
          <Form ref={formRef} defaultValues={info} onSubmit={() => onSubmit()}>
            <Cell.Group inset>
              <Form.Item style={{ flexDirection: "column", gap: "10px" }}>
                <Form.Label style={{ width: "100%" }}>
                  <Text>
                    营业执照
                    <Text style={{ fontSize: "12px", color: "red" }}>
                      图片最大不能超过500KB
                    </Text>
                  </Text>
                </Form.Label>
                <Form.Control>
                  <Uploader>
                    <View
                      style={{ display: "flex", flexWrap: "wrap", gap: "5px" }}
                    >
                      {info.businessLicense &&
                        info.businessLicense.split(",").map((item, index) => (
                          <Uploader.Image
                            key={index}
                            url={process.env.TARO_APP_API + item}
                            mode="aspectFill"
                            onClick={(e) => {
                              e.preventDefault();
                              e.stopPropagation();
                              priviewImage(info.businessLicense, index);
                            }}
                            onRemove={(e) => {
                              e.preventDefault();
                              e.stopPropagation();
                              let arr = info.businessLicense.split(",");
                              arr.splice(index, 1);
                              setInfo({
                                ...info,
                                businessLicense: arr.join(","),
                              });
                            }}
                          ></Uploader.Image>
                        ))}
                      <Uploader.Upload
                        onClick={() => onUpload("businessLicense", 1)}
                      />
                    </View>
                  </Uploader>
                </Form.Control>
              </Form.Item>
              <Form.Item style={{ flexDirection: "column", gap: "10px" }}>
                <Form.Label style={{ width: "100%" }}>
                  <Text>
                    企业铭牌
                    <Text style={{ fontSize: "12px", color: "red" }}>
                      (前台照片或营业牌匾等)图片最大不能超过500KB
                    </Text>
                  </Text>
                </Form.Label>
                <Form.Control>
                  <Uploader>
                    <View
                      style={{ display: "flex", flexWrap: "wrap", gap: "5px" }}
                    >
                      {info.enterpriseFamous &&
                        info.enterpriseFamous.split(",").map((item, index) => (
                          <Uploader.Image
                            key={index}
                            url={process.env.TARO_APP_API + item}
                            mode="aspectFill"
                            onClick={(e) => {
                              e.preventDefault();
                              e.stopPropagation();
                              priviewImage(info.enterpriseFamous, index);
                            }}
                            onRemove={(e) => {
                              e.preventDefault();
                              e.stopPropagation();
                              let arr = info.enterpriseFamous.split(",");
                              arr.splice(index, 1);
                              setInfo({
                                ...info,
                                enterpriseFamous: arr.join(","),
                              });
                            }}
                          ></Uploader.Image>
                        ))}
                      <Uploader.Upload
                        onClick={() => onUpload("enterpriseFamous", 1)}
                      />
                    </View>
                  </Uploader>
                </Form.Control>
              </Form.Item>
              <Form.Item style={{ flexDirection: "column", gap: "10px" }}>
                <Form.Label style={{ width: "100%" }}>
                  <Text>
                    身份证
                    <Text style={{ fontSize: "12px", color: "red" }}>
                      图片最大不能超过500KB
                    </Text>
                  </Text>
                </Form.Label>
                <Form.Control>
                  <Uploader>
                    <View
                      style={{ display: "flex", flexWrap: "wrap", gap: "5px" }}
                    >
                      {info.identityCard &&
                        info.identityCard.split(",").map((item, index) => (
                          <Uploader.Image
                            key={index}
                            url={process.env.TARO_APP_API + item}
                            mode="aspectFill"
                            onClick={(e) => {
                              e.preventDefault();
                              e.stopPropagation();
                              priviewImage(info.identityCard, index);
                            }}
                            onRemove={(e) => {
                              e.preventDefault();
                              e.stopPropagation();
                              let arr = info.identityCard.split(",");
                              arr.splice(index, 1);
                              setInfo({
                                ...info,
                                identityCard: arr.join(","),
                              });
                            }}
                          ></Uploader.Image>
                        ))}
                      <Uploader.Upload
                        onClick={() => onUpload("identityCard", 1)}
                      />
                    </View>
                  </Uploader>
                </Form.Control>
              </Form.Item>
            </Cell.Group>
            <View style={{ margin: "16px" }}>
              <Button block color="primary" formType="submit">
                保存
              </Button>
            </View>
          </Form>
        </View>
      </View>
      <Footer />
    </View>
  );
}
